package com.seguriapp.gwt.client;

import java.util.Date;

import net.customware.gwt.dispatch.client.DispatchAsync;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.PlaceController;
import com.seguriapp.common.gwt.client.AbstractSeguriAppPresenter;
import com.seguriapp.common.gwt.client.SeguriAppDisplay;
import com.seguriapp.entities.User;
import com.seguriapp.gwt.client.login.LoginPanel;
import com.seguriapp.gwt.client.login.LoginPanelPresenter;
import com.seguriapp.gwt.client.login.UserLoggedOffEvent;

public class PrincipalHeaderPresenter extends AbstractSeguriAppPresenter {

  public interface Display extends SeguriAppDisplay {

    void setPresenter(PrincipalHeaderPresenter cabeceraPrincipalPresenter);

    void showLoginPopup();

    LoginPanel getLoginPanel();

    void setLoggedInUserInfo(String username, Date lastDateLoggedIn);

  }

  private final Display display;
  private User user;

  public PrincipalHeaderPresenter(final DispatchAsync dispatchAsync, final EventBus eventBus, final PlaceController placeController, final Display display, final Date fechaActualServidor, final User user) {
    super(dispatchAsync, eventBus, placeController);
    this.display = display;
    this.display.setPresenter(this);
    this.user = user;
  }

  public void start() {
    if (user != null) {
      display.setLoggedInUserInfo(user.getUsername(), user.getLastDateLoggedIn());
    }
  }

  public void showLoginPopup() {
    initializeLoginEvent();
  }

  private void initializeLoginEvent() {
    new LoginPanelPresenter(dispatchAsync, eventBus, placeController, display.getLoginPanel());
    display.showLoginPopup();
  }

  public void logOffUser() {
    eventBus.fireEvent(new UserLoggedOffEvent());
  }

}
